<template>
  <div>
   <h1>Shopping Cart Example</h1>
    <ul class="box">
      <li
        v-for="(product, index) in products"
        :key="index"
      >
        <p>{{product.title}} 价格：{{product.price}} 库存：{{product.inventory}}</p>
        <button @click="addProductToCart(product)"> add to cart</button>
      </li>
    </ul>
    <h1>My cart</h1>
    <div class="cartlist">
      <ul>
        <li
          v-for="(item, index) in items"
          :key="index"
        >
          {{getTitle(item.id).title}}
          {{products.find(product =>product.id === item.id).title}} X {{item.quantity}}
        </li>
      </ul>
      <p>{{getTotal}}</p>
      <button @click="checkout(items)">checkout</button>
    </div>
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
const {
  mapState: cartMapState,
  mapActions: cartMapActions,
} = createNamespacedHelpers("cart");
const {
  mapState: productMapState,
  mapActions: productMapActions,
} = createNamespacedHelpers("product");
export default {
  data() {
    return {};
  },
  mounted() {
    this.getProducts();
  },
  methods: {
    ...productMapActions(["getProducts"]),
    ...cartMapActions(["addProductToCart", "checkout"]),
    getTitle(id) {
      return this.products.find((product) => product.id === id);
    },
    getPrice(id) {
      return this.products.find((product) => product.id === id).price;
    },
  },
  computed: {
    ...productMapState({
      products: (state) => state.all,
    }),
    ...cartMapState({
      items: (state) => state.items,
    }),
    getTotal() {
      var total = 0;
      if(this.items.length===0){
          return total;
      }
      this.items.forEach((e) => {
        total += this.getPrice(e.id) * e.quantity;
      });
      return total;
    },
  },
};
</script>

<style lang="scss">
li {
  list-style: none;
}
.box {
  li {
    list-style: none;
    font-size: 20px;
    color: red;
    button {
      width: 200px;
    }
  }
}
</style>